import { WebDriver, By, until } from 'selenium-webdriver';
import LarkClient from '../../../lark-sdk/LarkClient.js';
import { Query, SearchResult, SearchNote } from '../../lib/search.js';
import { AppConfig, getProfile } from '../../lib/utility.js';
import { systemBack } from '../utils/systemBack.js';
import { performSmoothScroll } from '../utils/scroll.js';
import { AndroidConfig } from '../../profile/android/android_config.js';
import { addUrlToFeishu, updateSearchTime } from './crud.js';
import { getAuthorProfile, getCurrentContent } from './crawl.js';
import { ContentStateMachine } from '../../lib/statemachine.js';

/**
 * 初始化飞书客户端
 */
async function initLarkClient() {
  const config = getProfile();
  return new LarkClient(config.larkAppID, config.larkAppSecret);
}

/**
 * 从飞书多维表格获取关键词
 */
async function getKeywordsFromLark(client:LarkClient,config:AppConfig): Promise<Query[]> {

  try {
    // read keyword form the feishu 
    const records = await client.readBitable(
      config.larkAppToken,
      config.bitableSousuoGuanjianciTableID
    );

    console.log('原始记录示例:', JSON.stringify(records[0], null, 2)); // 调试信息

    // Query results
    const queries: Query[] = [];
    for (const record of records) {
      // 处理关键词字段
      let keywords = record['关键词'];
      console.log('原始关键词数据:', keywords, '类型:', typeof keywords); // 调试信息
      
      if (typeof keywords === 'object' && keywords !== null) {
        // 飞书富文本字段通常有这些结构
        if (keywords.text) {
          keywords = keywords.text;
        } else if (Array.isArray(keywords) && keywords.length > 0) {
          keywords = keywords[0].text || keywords[0];
        } else {
          keywords = JSON.stringify(keywords);
        }
      }
      
      const keywordString = String(keywords || '');
      console.log('处理后的关键词:', keywordString); // 调试信息
      
      queries.push({
        recordId: record.record_id || '',
        ID: parseInt(record['编号']) || 0,
        keywords: keywordString,
      });
    }
    
    console.log(`从飞书获取到 ${queries.length} 个关键词`);
    return queries;
  } catch (error) {
    console.error('获取飞书关键词失败:', error);
    return [];
  }

}

/**
 * 执行基于飞书关键词的搜索
 */
async function doQuery(driver: WebDriver): Promise<SearchResult[]> {
  const results: SearchResult[] = [];
  
  // init project 
  const client = await initLarkClient();
  const config = getProfile();

  try {
    // 从飞书获取关键词列表
    const queries = await getKeywordsFromLark(client,config);
    
    if (queries.length === 0) {
      console.log('没有找到关键词，退出搜索');
      return results;
    }

    // 遍历每个关键词进行搜索
    for (const query of queries) {
      console.log(`正在搜索关键词: ${query.keywords} (ID: ${query.ID})`);

      try {
        // 点击搜索按钮 如果不存在就skip
        const searchButton = await driver.wait(
          until.elementLocated(By.xpath('//android.widget.Button[@content-desc="搜索"]'))
          , 1000
        );
        await searchButton.click();
      } catch {
        console.log(`关键词 "${query.keywords}" 未找到搜索按钮，直接输入关键词`);
      }
      
      await driver.sleep(3000);
      // 输入关键词
      const searchInput = await driver.findElement(
        By.className('android.widget.EditText'),
      );
      await searchInput.sendKeys(query.keywords);
      
      await driver.sleep(3000);
      // 执行搜索
      await driver.executeScript('mobile: performEditorAction', {
        action: 'search'
      });
      
      await driver.sleep(3000); // 等待搜索结果加载
      
      // 添加数据到feishu
      console.log("Start to add result....");
      await addNewData(client, config, query, driver);

      // 更新飞书中的最新搜索时间
      await updateSearchTime(client,config,query.recordId);

      console.log(`关键词 "${query.keywords}" 搜索完成`);
      await driver.sleep(3000);
      // 尝试使用系统返回键
      await systemBack(driver)
      // await systemBack(driver)
    }

  } catch (error) {
    console.error('搜索过程中出现错误:', error);
    throw error;
  }
  
  return results;
}

/**
 * 向飞书文档中添加数据
 * @param client 飞书客户端
 * @param config 配置信息
 * @param query 查询信息
 * @param driver WebDriver实例
 */
async function addNewData(client: LarkClient, config: AppConfig, query: Query, driver: WebDriver) {
  try {
    console.log('开始爬取搜索结果...');
    
    let scrollCount = 0; //scroll 次数
    let researchCount = 0;//搜索总量
    let order = 0 //排序

    while (researchCount < config.retreiveNoteCount) {
      console.log("剩余url待爬: ", config.retreiveNoteCount - researchCount)
      await driver.sleep(3000);
      const clickableElements = await driver.findElements(By.xpath('//android.view.View[@clickable="true"]'));
      console.log(`第${scrollCount + 1}次扫描，发现${clickableElements.length}个可点击元素`);

      for (let i = 0; i < clickableElements.length; i++) {
        // new state machine
        const contentMachine = new ContentStateMachine();

        try {
          const currentElements = await driver.findElements(By.xpath('//android.view.View[@clickable="true"]'));
          if (i >= currentElements.length) break;

          driver.sleep(3000);
          await currentElements[i].click();
          console.log(`成功点击第${i + 1}个元素 (滚动${scrollCount + 1})`);
          
          await driver.sleep(1000);
          
          // 获取作者主页
          const authorProfile = await getAuthorProfile(contentMachine,driver);
          console.log(`作者主页: ${authorProfile}`);
          // 返回上一页
          try {
            await driver.sleep(1000);
            await systemBack(driver);
          } catch (backError) {
            console.error('返回操作失败:', backError);
          }
          
          const contentdata = await getCurrentContent(contentMachine,driver);
          console.log("Contentdata: ",contentdata);

          // 获取当前页面url
          console.log(`页面URL: ${contentdata.link}`);
          if (contentdata.link) {
            researchCount++
          }
          
          await driver.sleep(1000);
          //添加到feishu
          await addUrlToFeishu(client, config, query, contentdata,authorProfile,order )
          order++
          
          // 返回上一页
          try {
            await driver.sleep(2000);
            await systemBack(driver);
          } catch (backError) {
            console.error('返回操作失败:', backError);
          }
          
          await driver.sleep(1500);

        } catch (elementError) {
          console.error(`处理元素时出错:`, elementError);
          
          // 如果是 driver 相关错误，抛出让上层处理
          if (elementError instanceof Error && 
              (elementError.message.includes('需要重新创建 WebDriver') || 
               elementError.message.includes('Driver 会话已损坏'))) {
            continue
          }
          
        }
      }
      
      // 向下scroll 获取数据
      await performSmoothScroll(driver, AndroidConfig.device.deviceName, 3, 'long');
      scrollCount++;
    }

    console.log(`已完成所有页面抓取，共收集URL: ${researchCount}个`);
    await systemBack(driver);
  } catch (error) {
    console.error('整体抓取流程失败:', error);
    
    // 如果是需要重新创建 driver 的错误，重新抛出
    if (error instanceof Error && 
        (error.message.includes('需要重新创建 WebDriver') || 
         error.message.includes('Driver 会话已损坏'))) {
      throw error;
    }
    
    try {
      await systemBack(driver);
    } catch (backError) {
      console.error('错误恢复失败');
      throw new Error('Driver 会话已损坏，需要重新创建');
    }
  } 
}


export { doQuery, getKeywordsFromLark };


